<template>
  <div class="process-list">
    <HeaderNav />
    <div class="list-container">
      <div class="list-header">
        <div class="header-left">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入流程名称"
            clearable
            style="width: 200px; margin-right: 15px;"
          />
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px; margin-right: 15px;"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
          <el-button type="primary" @click="searchProcesses">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="createProcess">新建流程</el-button>
        </div>
      </div>

      <div class="list-content">
        <el-table
          :data="processList"
          v-loading="loading"
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa' }"
        >
          <el-table-column prop="name" label="流程名称" min-width="150">
            <template #default="{ row }">
              <span class="process-name" @click="viewProcess(row)">{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
                {{ row.status === 'enabled' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="120" />
          <el-table-column prop="createdAt" label="创建时间" width="180" />
          <el-table-column prop="useCount" label="使用次数" width="100" />
          <el-table-column prop="version" label="版本" width="80" />
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="editProcess(row)">编辑</el-button>
              <el-button
                :type="row.status === 'enabled' ? 'warning' : 'success'"
                link
                @click="toggleStatus(row)"
              >
                {{ row.status === 'enabled' ? '禁用' : '启用' }}
              </el-button>
              <el-button type="primary" link @click="copyProcess(row)">复制</el-button>
              <el-button type="primary" link @click="viewInstances(row)">监控</el-button>
              <el-button type="danger" link @click="deleteProcess(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model="pagination.currentPage"
            :page-sizes="[10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 流程监控对话框 -->
    <el-dialog
      title="流程监控"
      v-model="monitorVisible"
      width="70%"
    >
      <div class="monitor-content">
        <el-tabs v-model="activeMonitorTab" @tab-change="handleTabChange">
          <el-tab-pane label="运行实例" name="instances">
            <el-table :data="processInstances" style="width: 100%">
              <el-table-column prop="id" label="实例ID" width="100" />
              <el-table-column prop="startTime" label="启动时间" width="180" />
              <el-table-column prop="currentNode" label="当前节点" width="150" />
              <el-table-column prop="assignee" label="处理人" width="120" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getInstanceStatusType(row.status)">
                    {{ getInstanceStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="duration" label="已用时" width="120" />
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button type="primary" link @click="viewInstanceDetail(row)">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="阻塞节点" name="blocked">
            <el-table :data="blockedNodes" style="width: 100%">
              <el-table-column prop="nodeName" label="节点名称" width="150" />
              <el-table-column prop="processName" label="流程名称" width="150" />
              <el-table-column prop="assignee" label="处理人" width="120" />
              <el-table-column prop="blockTime" label="阻塞时间" width="180" />
              <el-table-column prop="duration" label="已阻塞时长" width="120" />
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button type="primary" link @click="remindAssignee(row)">提醒处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="monitorVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 版本管理对话框 -->
    <el-dialog
      title="版本管理"
      v-model="versionVisible"
      width="60%"
    >
      <div class="version-content">
        <el-table :data="processVersions" style="width: 100%">
          <el-table-column prop="version" label="版本号" width="100" />
          <el-table-column prop="creator" label="修改人" width="120" />
          <el-table-column prop="updateTime" label="修改时间" width="180" />
          <el-table-column prop="description" label="修改说明" />
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="primary" link @click="viewVersion(row)">查看</el-button>
              <el-button type="primary" link @click="rollbackVersion(row)">回滚</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import { getProcessList, deleteProcess as apiDeleteProcess, toggleProcessStatus as apiToggleProcessStatus, getProcessInstances as apiGetProcessInstances, getBlockedNodes as apiGetBlockedNodes } from '@/api/workflow'

// 响应式数据
const searchForm = ref({
  name: '',
  status: ''
})

const processList = ref([])

const loading = ref(false)
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 3
})

const monitorVisible = ref(false)
const versionVisible = ref(false)
const activeMonitorTab = ref('instances')
const selectedProcess = ref(null)

// 监控数据
const processInstances = ref([])

const blockedNodes = ref([])

const processVersions = ref([])

// 查询流程
const searchProcesses = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      name: searchForm.value.name,
      status: searchForm.value.status
    }

    const response = await getProcessList(params)

    if (response.code === 200) {
      processList.value = response.data.list
      pagination.value.total = response.data.pagination.total
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(response.message || '查询失败')
    }
  } catch (error) {
    console.error('查询流程失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetSearch = () => {
  searchForm.value = {
    name: '',
    status: ''
  }
  searchProcesses()
}

// 创建流程
const createProcess = () => {
  // 跳转到流程设计页面
  window.location.hash = '#/workflow/designer'
}

// 编辑流程
const editProcess = (row) => {
  // 跳转到流程设计页面并加载指定流程
  console.log('编辑流程:', row)
  window.location.hash = '#/workflow/designer'
}

// 切换流程状态
const toggleStatus = async (row) => {
  ElMessageBox.confirm(
    `确定要${row.status === 'enabled' ? '禁用' : '启用'}流程"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await apiToggleProcessStatus(row.id)

      if (response.code === 200) {
        row.status = response.data.status
        ElMessage.success(`${row.status === 'enabled' ? '启用' : '禁用'}成功`)
      } else {
        ElMessage.error(response.message || '操作失败')
      }
    } catch (error) {
      console.error('切换流程状态失败:', error)
      ElMessage.error('操作失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 复制流程
const copyProcess = (row) => {
  ElMessageBox.confirm(
    `确定要复制流程"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('流程复制成功')
  }).catch(() => {
    // 用户取消操作
  })
}

// 查看流程
const viewProcess = (row) => {
  ElMessage.info(`查看流程: ${row.name}`)
}

// 删除流程
const deleteProcess = async (row) => {
  ElMessageBox.confirm(
    `确定要删除流程"${row.name}"吗？此操作不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(async () => {
    try {
      const response = await apiDeleteProcess(row.id)

      if (response.code === 200) {
        const index = processList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          processList.value.splice(index, 1)
          pagination.value.total--
          ElMessage.success('删除成功')
        }
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除流程失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 查看监控
const viewInstances = async (row) => {
  selectedProcess.value = row

  // 获取流程实例列表
  try {
    const response = await apiGetProcessInstances(row.id, {
      page: 1,
      pageSize: 10
    })

    if (response.code === 200) {
      processInstances.value = response.data.list
    } else {
      ElMessage.error(response.message || '获取实例列表失败')
    }
  } catch (error) {
    console.error('获取流程实例列表失败:', error)
    ElMessage.error('获取实例列表失败')
  }

  monitorVisible.value = true
}

// 处理标签切换
const handleTabChange = async (tabName) => {
  if (tabName === 'blocked' && blockedNodes.value.length === 0) {
    // 获取阻塞节点列表
    try {
      const response = await apiGetBlockedNodes({
        page: 1,
        pageSize: 10
      })

      if (response.code === 200) {
        blockedNodes.value = response.data.list
      } else {
        ElMessage.error(response.message || '获取阻塞节点列表失败')
      }
    } catch (error) {
      console.error('获取阻塞节点列表失败:', error)
      ElMessage.error('获取阻塞节点列表失败')
    }
  }
}

// 查看实例详情
const viewInstanceDetail = (row) => {
  ElMessage.info(`查看实例详情: ${row.id}`)
}

// 提醒处理人
const remindAssignee = (row) => {
  ElMessage.success(`已发送提醒给 ${row.assignee}`)
}

// 获取实例状态类型
const getInstanceStatusType = (status) => {
  const types = {
    processing: '',
    blocked: 'warning',
    completed: 'success',
    cancelled: 'info'
  }
  return types[status] || ''
}

// 获取实例状态文本
const getInstanceStatusText = (status) => {
  const texts = {
    processing: '处理中',
    blocked: '阻塞',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

// 查看版本
const viewVersion = (row) => {
  ElMessage.info(`查看版本: ${row.version}`)
}

// 回滚版本
const rollbackVersion = (row) => {
  ElMessageBox.confirm(
    `确定要回滚到版本${row.version}吗？`,
    '版本回滚',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success(`已回滚到版本${row.version}`)
  }).catch(() => {
    // 用户取消操作
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  searchProcesses()
}

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  searchProcesses()
}

// 组件挂载时查询数据
onMounted(() => {
  searchProcesses()
})
</script>

<style scoped lang="scss">
.process-list {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f5f7fa;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
  }

  .header-right {
    display: flex;
    align-items: center;
  }
}

.list-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;

  .process-name {
    color: #409eff;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 20px 0;
}

.monitor-content,
.version-content {
  min-height: 400px;
}
</style>
